<template>
	<view class="container">
		<view class="left-bottom-sign"></view>
		<view class="back-btn iconfont iconzuojiantou-01" @click="navBack"></view>
		<view class="right-top-sign"></view>
		<!-- 设置白色背景防止软键盘把下部绝对定位元素顶上来盖住输入框等 -->
		<!-- #ifdef H5 || APP-PLUS -->
		<view class="wrapper">
			<view class="left-top-sign">LOGIN</view>
			<view class="welcome">
				欢迎登录
			</view>
			<view class="input-content">
				<view class="input-item">
					<text class="tit">手机号码</text>
					<input 
						type="number" 
						:value="mobile" 
						placeholder="请输入手机号码"
						maxlength="11"
						data-key="mobile"
						@input="inputChange"
					/>
				</view>
				<view v-if="passwordLogin" class="input-item">
					<text class="tit">密码</text>
					<input 
						type="text" 
						:value="password" 
						placeholder="8-18位不含特殊字符的数字、字母组合"
						placeholder-class="input-empty"
						maxlength="20"
						password 
						data-key="password"
						@input="inputChange"
						@confirm="toLogin"
					/>
				</view>
				<view v-if="smsCodeLogin" class="input-item">
					<text class="tit">验证码</text>
					<view class="code">
						<input 
							type="text" 
							:value="code" 
							placeholder="请输入验证码"
							placeholder-class="input-empty"
							maxlength="20"
							data-key="code"
							@input="inputChange"
							@confirm="toLogin"
						/>
						<view style="color: #ff7f50;">获取验证码</view>
					</view>
				</view>
			</view>
			<button class="confirm-btn" @click="toLogin" :disabled="logining">登录</button>
			<view class="forget-section" @click="toForgetPage">
				忘记密码?
			</view>
		</view>
		<view class="register-section">
			还没有账号?
			<text @click="toRegisterPage">马上注册</text>
		</view>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<view class="wrapper">
			<view class="left-top-sign">LOGIN</view>
			<view class="welcome">
				欢迎登录
			</view>
			<button v-if="!hasUserInfo" class="confirm-btn" open-type="getUserInfo" lang="zh_CN" @getuserinfo="bindGetUserInfo">
				<view class="zy-text-big zy-text-bold" style="color: #fff;">微信授权登录</view>
			</button>
			<view v-else>
				<view class="zy-text-big zy-text-bold zy-logined">您已成功登录，自动返回上一页</view>
				<view class="zy-text-big zy-text-bold zy-logined" style="margin-top: 20upx;">如未跳转，请手动返回上一页</view>
			</view>
			
		</view>
		<!-- #endif -->
		<!-- #ifdef H5 -->
		<view class="wrapper">
			<view class="left-top-sign">LOGIN</view>
			<view class="welcome">
				欢迎登录
			</view>
			<button v-if="!hasUserInfo" class="confirm-btn" @click="gzhLogin" :disabled="logining">
				<view class="zy-text-big zy-text-bold" style="color: #fff;">微信授权登录</view>
			</button>
			<view v-else>
				<view class="zy-text-big zy-text-bold zy-logined">您已成功登录，自动返回上一页</view>
				<view class="zy-text-big zy-text-bold zy-logined" style="margin-top: 20upx;">如未跳转，请手动返回上一页</view>
			</view>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		REGISTER_PAGE,
		FORGET_PAGE
	} from '@/common/page-url.js'
	import {
		FRONT_BASE_URL,
		USER_OPENID,
		USER_TOKEN_KEY,
		nullToStr,
		navTo,
		redTo,
		doPostForm,
		doGet,
		SHARE_CODE,
		MY_SHARE_CODE,
		USER_ID,
		USER_PHONE,
		USER_ROLES,
		MALL_DISTRIBUTOR_FLAG,
		HAS_USER_INFO,
		REFRESH_CART,
		showInfoToast
	} from '@/common/util.js'
	import * as ResponseStatus from '@/common/response-status.js'
	export default{
		data(){
			return {
				passwordLogin: false,
				smsCodeLogin: true,
				mobile: '',
				password: '',
				code: '',
				logining: false,
				fromUrl: '/pages/index/index',
				hasUserInfo: false,
				userInfo: {},
				urls: {
					xcxSaveUserInfoUrl: '/wx-auth/xcx-userdetail',
					xcxLoginUrl: '/wx-auth/xcx',
					getUserDetailUrl: '/user-userdetail/user/get',
					getUserRolesUrl: '/user-role/user/list',
				},
			}
		},
		onLoad(options){
			this.fromUrl = options.fromUrl
			this.judgeLogin()
		},
		methods: {
			/**
			 * 检查登录
			 * @param {Object} type
			 */
			judgeLogin() {
				const userToken = uni.getStorageSync(USER_TOKEN_KEY);
				if (userToken) {
					// #ifndef MP-ALIPAY || H5 || APP-PLUS
					uni.checkSession({
						success: () =>  {
							// 用户token存在，且微信登录状态正常，则直接获取用户信息
							this.getUserDetail()
						},
						fail: () => {
							// 重新授权登录，获取新session_key
							this.xcxLogin()
						},
					})
					// #endif
				} else {
					// #ifdef MP-WEIXIN
					this.xcxLogin()
					// #endif
					// #ifdef H5
					this.gzhLogin()
					// #endif
				}
			},
			/**
			 * 小程序登入
			 */
			xcxLogin() {
				var myThis = this;
				uni.login({
					provider: 'weixin',
					success: function(wxRes) {
						let theShareCode = uni.getStorageSync(SHARE_CODE)
						if (!theShareCode) {
							theShareCode = null
						}
						const data = {
							code: wxRes.code,
							shareCode: theShareCode
						}
						doGet(myThis.urls.xcxLoginUrl, data, {}, false).then(response => {
							let [error, res] = response;
							if (res.data.code === ResponseStatus.OK) {
								// 保存用户的openid和token
								uni.setStorageSync(USER_OPENID, res.data.data[1]);
								uni.setStorageSync(USER_TOKEN_KEY, res.data.data[2]);
								if (res.data.data[0] === 'firstLogin') {
									// 第一次小程序登录，需要点击登录按钮，才能获取用户信息再保存用户信息
									uni.removeStorageSync(SHARE_CODE);
								} else {
									// 第二次开始不需要点击登录按钮，而是直接从后台获取用户信息
									myThis.getUserDetail();
								}
							} else {
								showInfoToast(res.data.message);
							}
						}).catch(err => {
							console.log(err);
						})
					}
				})
			},
			gzhLogin() {
				const shareCode = uni.getStorageSync(SHARE_CODE);
				const data = {
					extraParams : FRONT_BASE_URL + '#' + fromUrl + '__' + FRONT_BASE_URL + '#' + fromUrl + '__' + (shareCode ? shareCode : 'shareCode')
				}
				doGet('/wx-auth/to-gzh', data, {}, false).then(response => {}).catch(err => {
					console.log(err);
				})
			},
			/**
			 * 获取用户详情
			 */
			getUserDetail() {
				uni.showLoading({
					title: '登录中...'
				})
				doGet(this.urls.getUserDetailUrl, {}, {}, true).then(response => {
					uni.hideLoading()
					let [error, res] = response;
					if (res.data.code === ResponseStatus.OK) {
						if (res.data.data.total > 0) {
							var userInfo = nullToStr(res.data.data.rows[0]);
							if (userInfo.userDetailNickname) {
								this.userInfo.nickname = userInfo.userDetailNickname;
							}
							if (userInfo.userDetailHeadicon) {
								this.userInfo.headicon = userInfo.userDetailHeadicon;
								if (this.userInfo.headicon && this.userInfo.headicon.indexOf('http') < 0) {
									this.userInfo.headicon = FRONT_BASE_URL + this.userInfo.headicon;
								}
							}
							if (userInfo.userDetailGender) {
								this.userInfo.gender = userInfo.userDetailGender;
							}
							if (userInfo.userPhone) {
								this.hasPhone = true
								this.userInfo.phone = userInfo.userPhone;
							}
							if (this.userInfo.nickname && this.userInfo.headicon) {
								// 已经获取到了用户信息
								this.hasUserInfo = true;
								uni.setStorageSync(USER_ID, userInfo.userId);
								uni.setStorageSync(HAS_USER_INFO, true);
								// 加载其他用户数据
								this.loadOtherUserData()
								uni.setStorageSync(REFRESH_CART, true)
								setTimeout(() => {
									uni.navigateBack()
								}, 1000)
							} else {
								uni.setStorageSync(HAS_USER_INFO, false);
							}
							uni.setStorageSync(USER_PHONE, userInfo.userPhone);
							uni.setStorageSync(MY_SHARE_CODE, userInfo.userDetailShareCode)
						}
					} else if (res.data.code === ResponseStatus.AUTHENTICATION_TOKEN_ERROR) {
						// 如果token过期了，则直接使用小程序登录，获取最新的token
						uni.removeStorageSync(USER_TOKEN_KEY);
						uni.removeStorageSync(USER_OPENID);
						uni.removeStorageSync(USER_ID)
						uni.setStorageSync(HAS_USER_INFO, false);
						this.xcxLogin();
					} else {
						showInfoToast(res.data.message);
					}
				}).catch(err => {
					console.log(err);
				})
			},
			/**
			 * 获取用户的角色信息
			 */
			getUserRoles() {
				doGet(this.urls.getUserRolesUrl, {}, {}, true).then(response => {
					let [error, res] = response;
					if (res.data.code === ResponseStatus.OK) {
						var rolesArrey = []
						uni.setStorageSync(MALL_DISTRIBUTOR_FLAG, false)
						res.data.data.rows.forEach(item => {
							rolesArrey.push(item.roleTitle);
							if (item.roleTitle.indexOf('sys_mall_distributor_v') != -1) {
								uni.setStorageSync(MALL_DISTRIBUTOR_FLAG, true)
								this.isDistribution = true
							}
						})
						uni.setStorageSync(USER_ROLES, rolesArrey);
					} else {
						showInfoToast(res.data.message);
					}
				}).catch(err => {
					console.log(err);
				})
			},
			/**
			 * 获取用户信息
			 * @param {Object} e
			 */
			bindGetUserInfo(e) {
				const openId = uni.getStorageSync(USER_OPENID);
				const data = {
					openid: openId,
					nickname: e.detail.userInfo.nickName,
					headicon: e.detail.userInfo.avatarUrl,
					gender: e.detail.userInfo.gender
				};
				uni.showLoading({
					title: '登录中...'
				})
				doPostForm(this.urls.xcxSaveUserInfoUrl, data, {}, false).then(response => {
					let [error, res] = response;
					if (res.data.code === ResponseStatus.OK) {
						this.hasUserInfo = true;
						this.userInfo.nickname = data.nickname;
						this.userInfo.headicon = data.headicon;
						// 设置已登录并且获取用户信息
						uni.setStorageSync(HAS_USER_INFO, true)
						// 加载其他用户数据
						this.loadOtherUserData()
					} else {
						showInfoToast(res.data.message);
					}
					uni.hideLoading()
				}).catch(err => {
					console.log(err)
				})
			},
			loadOtherUserData() {
				this.getUserRoles()
			},
			inputChange(e){
				const key = e.currentTarget.dataset.key;
				this[key] = e.detail.value;
			},
			navBack(){
				uni.navigateBack();
			},
			/**
			 * 前往找回密码页面
			 */
			toForgetPage() {
				redTo(FORGET_PAGE, false);
			},
			/**
			 * 前往注册页面
			 */
			toRegisterPage(){
				redTo(REGISTER_PAGE, false);
			},
			async toLogin(){
				this.logining = true;
				const {mobile, password} = this;
			}
		},

	}
</script>

<style lang='scss'>
	@import '@/common/zywork-main.scss';
	@import '@/components/zywork-icon/iconfont.css';
	page{
		background: #fff;
	}
	.container{
		padding-top: 115px;
		position:relative;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		background: #fff;
	}
	.wrapper{
		position:relative;
		z-index: 90;
		background: #fff;
		padding-bottom: 40upx;
	}
	.left-top-sign{
		font-size: 120upx;
		color: $page-color-base;
		position:relative;
		left: -16upx;
	}
	.right-top-sign{
		position:absolute;
		top: 80upx;
		right: -30upx;
		z-index: 95;
		&:before, &:after{
			display:block;
			content:"";
			width: 400upx;
			height: 80upx;
			background: #b4f3e2;
		}
		&:before{
			transform: rotate(50deg);
			border-radius: 0 50px 0 0;
		}
		&:after{
			position: absolute;
			right: -198upx;
			top: 0;
			transform: rotate(-50deg);
			border-radius: 50px 0 0 0;
			/* background: pink; */
		}
	}
	.left-bottom-sign{
		position:absolute;
		left: -270upx;
		bottom: -320upx;
		border: 100upx solid #d0d1fd;
		border-radius: 50%;
		padding: 180upx;
	}
	.welcome{
		position:relative;
		left: 50upx;
		top: -90upx;
		font-size: 46upx;
		color: #555;
		text-shadow: 1px 0px 1px rgba(0,0,0,.3);
	}
	.input-content{
		padding: 0 60upx;
	}
	.input-item{
		display:flex;
		flex-direction: column;
		align-items:flex-start;
		justify-content: center;
		padding: 0 30upx;
		background:$page-color-light;
		height: 120upx;
		border-radius: 4px;
		margin-bottom: 50upx;
		&:last-child{
			margin-bottom: 0;
		}
		.tit{
			height: 50upx;
			line-height: 56upx;
			font-size: $font-sm+2upx;
			color: $font-color-base;
		}
		.code {
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-between;
			width: 100%;
		}
		input{
			height: 60upx;
			font-size: $font-base + 2upx;
			color: $font-color-dark;
		}	
	}

	.confirm-btn{
		width: 630upx;
		height: 76upx;
		line-height: 76upx;
		border-radius: 50px;
		margin-top: 70upx;
		background: $uni-color-primary;
		color: #fff;
		font-size: $font-lg;
		&:after{
			border-radius: 100px;
		}
	}
	.forget-section{
		font-size: $font-sm+2upx;
		color: $font-color-spec;
		text-align: center;
		margin-top: 40upx;
	}
	.register-section{
		position:absolute;
		left: 0;
		bottom: 50upx;
		width: 100%;
		font-size: $font-sm+2upx;
		color: $font-color-base;
		text-align: center;
		text{
			color: $font-color-spec;
			margin-left: 10upx;
		}
	}
	
	.zy-wx-btn {
		line-height: 1;
		display: inline;
		padding: 0;
	}
	
	.zy-logined {
		color: #ff7f50; 
		text-align: center;
		margin-top: 70upx;
	}
</style>
